﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using OpenNETCF.Desktop.Communication;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace OutlookSMSClient
{
    partial class SendSMSRegion
    {
        #region Form Region Factory

        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Appointment)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Contact)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
        [Microsoft.Office.Tools.Outlook.FormRegionName("OulookSMSClient.SendSMSRegion")]
        public partial class SendSMSRegionFactory
        {
            // Occurs before the form region is initialized.
            // To prevent the form region from appearing, set e.Cancel to true.
            // Use e.OutlookItem to get a reference to the current Outlook item.
            private void SendSMSRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
            {
            }
        }

        #endregion

        // Occurs before the form region is displayed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void SendSMSRegion_FormRegionShowing(object sender, System.EventArgs e)
        {
        }

        // Occurs when the form region is closed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void SendSMSRegion_FormRegionClosed(object sender, System.EventArgs e)
        {
        }

        private Outlook.Items contactItems;
        private List<ListItem> list = new List<ListItem>();

        public List<ListItem> NumberList
        {
            get { return list; }
            set { list = value; }
        }

        private void SendSMSRegion_Load(object sender, EventArgs e)
        {
            Outlook.Application objOutlook = new Outlook.Application();
            Outlook.NameSpace outlookNameSpace = objOutlook.GetNamespace("MAPI");
            Outlook.MAPIFolder contactsFolder = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
             contactItems= contactsFolder.Items;
             

            CheckConditions();
            txtMessage.TextChanged += new EventHandler(txtMessage_TextChanged);
        }


        void txtMessage_TextChanged(object sender, EventArgs e)
        {
            CalculateNumMessages();            
        }

        private void CalculateNumMessages(){
            int nRec = 0;
            int nMex = 0;
            nRec = lstContacts.CheckedItems.Count;
            nMex = (int)(txtMessage.TextLength / 160);
            int res=nRec*(nMex+1);
            lblNumMessages.Text = res.ToString() + " message(s)";
        }

        private bool CheckConditions()
        {
            RAPI r = new RAPI();
            if (r.DevicePresent)
            {
                LoadAll();
                r.Dispose();
                return true;
            }
            else {
                UnloadAll();
                r.Dispose();
                return false;
            }
        }

        private void UnloadAll()
        {
            splitContainer1.Panel1.Enabled = false;
            splitContainer1.Panel2.Enabled = true;            
            lblAdvice.Visible = true;
        }

        private void LoadAll()
        {
            splitContainer1.Panel1.Enabled = true;
            splitContainer1.Panel2.Enabled = false;
            lblAdvice.Visible = false;
            
            ContactsTask();
            PopulateList();
            
            txtMessage.ResetText();
        }

        private void PopulateList()
        {
            list.Clear();
            string ls = global::OutlookSMSClient.Properties.Settings.Default.Lists;
            if (String.IsNullOrEmpty(ls)) return;

            string[] lists = ls.Split('!');
            foreach (string str in lists) {
                ListItem temp = new ListItem();
                string[] fields = str.Split('?');
                temp.Name= fields[0];
                foreach (string num in fields[1].Split('$')) {
                    temp.Numbers.Add(num);
                }
                list.Add(temp);
            }
            RefreshCombo();
        }

        private void RefreshCombo()
        {
            cmbQuickList.Items.Clear();
            foreach (ListItem it in list) {
                cmbQuickList.Items.Add(it.Name);
            }
        }

        

        private void ContactsTask() {
                    
            bool bloop = false;
            lstContacts.Items.Clear();
            try
            {
                do
                {
                    try
                    {
                        Outlook.ContactItem contact = (Outlook.ContactItem)contactItems.GetNext();
                        if (contact != null)
                        {

                            if (!String.IsNullOrEmpty(contact.MobileTelephoneNumber))
                                lstContacts.Items.Add(contact.FullName.PadRight(30) + " :" + contact.MobileTelephoneNumber);

                            bloop = true;
                        }
                        else
                        {
                            bloop = false;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                } while (bloop == true);
            }
            catch (Exception ex)
            {
                return;
            } 

        }

        private void cmdRefresh_Click(object sender, EventArgs e)
        {
            CheckConditions();
        }

        private void cmdSend_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtMessage.Text)) return;

                SendMessage();
                SaveMessage();
                txtMessage.ResetText();
           
        }

        private void SaveMessage()
        {
            
        }

        private void SendMessage()
        {
            TcpClient cl;
            bool found=false;
            List<string> messages=GetFormattedMessage();

            while (!found) {
                cl = new TcpClient();
                try
                {
                    cl.Connect(Utilities.GetIP(),Utilities.GetPort());
                    StreamWriter wr = new StreamWriter(cl.GetStream());
                    foreach (object obj in lstContacts.CheckedItems) {
                        string mobo = obj.ToString().Split(':')[1];
                        
                        wr.WriteLine(mobo + "$" + txtMessage.Text);
                        //foreach (string msg in messages){
                        //    wr.WriteLine(mobo + "$" + msg);
                        //    wr.Flush();
                        //}
                        
                    }
                    cl.Close();
                    found = true;
                    MessageBox.Show("Your message has been sent!", "Message Sent", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch {
                   switch (MessageBox.Show("PocketPC server seems to be stopped or maybe it listens on different settings: do you want to change settings?",
                        "Attention!",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Information)){
                       case DialogResult.Yes:                           
                                new ChangeSettings().ShowDialog();
                                break;
                       case DialogResult.No:
                                MessageBox.Show("Please activate server and click OK!", "Attention!");
                                break;
                       case DialogResult.Cancel:
                                MessageBox.Show("Not sent!", "Information!");
                                return;                                
                    }
                    
                    continue;
                }
            }




        }

        private List<string> GetFormattedMessage() {
            int count = 0;
            StringBuilder strTemp = new StringBuilder(160);
            List<string> toReturn = new List<string>();
            foreach (char c in txtMessage.Text.ToCharArray())
            {
                if (count == 160) {
                    count = 0;
                    toReturn.Add(strTemp.ToString());
                    strTemp = new StringBuilder(160);
                    continue;
                }
                strTemp.Append(c);
                count++;
            }
            toReturn.Add(strTemp.ToString());
            return toReturn;
        }

        private void lstContacts_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            CalculateNumMessages();
        }

        private void cmdClear_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lstContacts.Items.Count; i++) {
                lstContacts.SetItemChecked(i, false);
            }
            
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtNewList.Text) || lstContacts.CheckedItems.Count == 0)
            {
                MessageBox.Show("Please select at least one item and specify a valid name!", "Attention!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ListItem it = new ListItem();
            it.Name= txtNewList.Text;

            foreach (object obj in lstContacts.CheckedItems)
            {
                it.Numbers.Add(obj.ToString().Split(':')[1]);
            }
            list.Add(it);
            Utilities.SaveSettings(list);
            RefreshCombo();
            MessageBox.Show("Quick List Added!", "Completed!",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void cmbQuickList_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            var item = from tmp in list
                       where tmp.Name == cmbQuickList.Text
                       select tmp;

            for (int i = 0; i < lstContacts.Items.Count; i++) {
                string num = lstContacts.Items[i].ToString().Split(':')[1];
                if (item.First().Numbers.Contains(num)) 
                    lstContacts.SetItemChecked(i, true);
                else 
                    lstContacts.SetItemChecked(i, false);
            }

            
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(cmbQuickList.Text)) {
                string name = cmbQuickList.Text;
                if (MessageBox.Show("Are you sure you want to delete " + name + " list?", "Attention!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var item = from tmp in list
                               where tmp.Name == cmbQuickList.Text
                               select tmp;
                    ListItem it = item.First();
                    list.Remove(it);
                    Utilities.SaveSettings(list);
                    RefreshCombo();
                }
            }
        }

        private void lstContacts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstContacts.SelectedItem != null)
            {
                cmdStartCall.Visible = true;
            }
            else
            {
                cmdStartCall.Visible = false;
            }
        }

        private void cmdStartCall_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstContacts.SelectedItem != null)
                {
                    object obj = lstContacts.SelectedItem;
                    string mobo = obj.ToString().Split(':')[1];
                    string command = "CALL$" + mobo;
                    bool found = false;
                    TcpClient cl;
                    while (!found)
                    {
                        cl = new TcpClient();
                        try
                        {
                            cl.Connect(Utilities.GetIP(), Utilities.GetPort());
                            StreamWriter wr = new StreamWriter(cl.GetStream());
                            

                            wr.WriteLine(command);
                            wr.Flush();
                               
                            cl.Close();
                            found = true;
                            
                        }
                        catch
                        {
                            switch (MessageBox.Show("PocketPC server seems to be stopped or maybe it listens on different settings: do you want to change settings?",
                                 "Attention!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information))
                            {
                                case DialogResult.Yes:
                                    new ChangeSettings().ShowDialog();
                                    break;
                                case DialogResult.No:
                                    MessageBox.Show("Please activate server and click OK!", "Attention!");
                                    break;
                                case DialogResult.Cancel:
                                    MessageBox.Show("Not sent!", "Information!");
                                    return;
                            }

                            continue;
                        }
                    }
                }
                
            }
            catch
            {
                MessageBox.Show("Error while trying to call your contact!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

      

       
        
    }
}
